package com.care.inquiry.server.im.handler;

import com.alibaba.fastjson2.JSON;

import com.care.inquiry.server.im.IMServer;
import com.care.inquiry.server.im.MessageType;
import com.care.inquiry.server.im.Result;
import com.care.inquiry.server.im.command.ChatMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

/**
 * @version: java version 1.8
 * @author: cuiweijie
 * @date: 2024-03-25 22:14
 */
public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame){
        try {
            ChatMessage chat = JSON.parseObject(frame.text(), ChatMessage.class);
            switch (MessageType.match(chat.getType())){
                case PRIVATE:{
                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
                    ctx.channel().writeAndFlush(Result.fail("消息发送失败,请选择发送对象"));
                    return;
                       }
                    Channel channel = IMServer.USERS.get(chat.getTarget());
                    if(null==channel ||!channel.isActive()){
                            ctx.channel().writeAndFlush(Result.fail("消息对方"+chat.getTarget()+"不在线"));
                            break;
                    }else {
                        channel.writeAndFlush(Result.success("私聊消息("+chat.getNickname()+")",chat.getContent()));
                        break;
                    }
                }
                default:ctx.channel().writeAndFlush(Result.fail("不支持消息类型"));
            }
        }catch (Exception e){
                ctx.channel().writeAndFlush(Result.fail("发送小消息格式错误,请确认再试"));
        }
    }
}
